import moment from "moment";
import { toFixed } from "./utils";
import qs from "qs";
const weeks = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];
export function getValue(value, len = 5) {
  let _value = value;
  let max_str = _value + "";
  let isPoint = max_str.includes(".");
  if (isPoint) {
    if (max_str.length >= 5) {
      _value = parseFloat(max_str.slice(0, len));
    } else {
      _value = parseFloat(max_str.padEnd(len, "0").slice(0, len));
    }
  } else {
    if (max_str.length >= len) {
      _value = value;
    } else {
      _value = _value + ".";
      if (_value.length == len) {
        _value = value;
      } else {
        _value = parseFloat(_value.padEnd(len, "0").slice(0, len));
      }
    }
  }

  return _value;
}

export function getFixed(value) {
  return Math.round(value * 10) / 10;
}

export function getEchartsDataRange(curDate, type) {
  switch (type) {
    case "day": {
      return [
        moment(curDate).startOf("day").format("YYYY-MM-DD HH:mm:ss"),
        moment(curDate).endOf("day").format("YYYY-MM-DD HH:mm:ss"),
      ];
    }
    case "week": {
      moment.locale("en", {
        week: { dow: 1 }, // Monday is the first day of the week
      });
      const monday = moment(curDate).startOf("week");
      const sunday = moment(curDate).endOf("week");
      console.log(monday.format("YYYY-MM-DD"), sunday.format("YYYY-MM-DD"));
      return [monday.format("YYYY-MM-DD"), sunday.format("YYYY-MM-DD")];
    }
    case "month": {
      const startOfMonth = moment(curDate)
        .startOf("month")
        .format("YYYY-MM-DD");
      const endOfMonth = moment(curDate).endOf("month").format("YYYY-MM-DD");
      return [startOfMonth, endOfMonth];
    }
    case "year": {
      return [
        moment(curDate).startOf("year").format("YYYY-MM-DD"),
        moment(curDate).endOf("year").format("YYYY-MM-DD"),
      ];
    }
  }
}

export function getWeekOfMonth(date) {
  moment.locale("en", {
    week: { dow: 1 }, // Monday is the first day of the week
  });
  const now = moment(date);
  const startOfMonth = now.clone().startOf("month");
  const endOfMonth = now.clone().endOf("month");
  const today = now.clone().startOf("day");
  let current = startOfMonth;
  let weeks = 0;

  while (current.isBefore(endOfMonth)) {
    const endOfWeek = current.clone().endOf("week");
    if (endOfWeek.isBefore(endOfMonth) || endOfWeek.isSame(today, "day")) {
      weeks++;
      if (endOfWeek.isSame(today, "day")) {
        return weeks;
      }
    }
    current = endOfWeek.clone().add(1, "day");
  }

  return weeks;
}

export function getEchartsDataDesc(curDate, type) {
  let curDateMoment = moment(curDate);
  switch (type) {
    case "day": {
      return curDateMoment.format("YYYY年MM月DD日");
    }
    case "week": {
      return `${curDateMoment.year()}年${curDateMoment.month() + 1
        }月第${getWeekOfMonth(curDate)}周`;
    }
    case "month": {
      return curDateMoment.format("YYYY年MM月");
    }
    case "year": {
      return curDateMoment.format("YYYY年");
    }
  }
}

function getDayEchartData(datas = [], dateRange) {
  let xAxis = [];
  let yAxis = [];
  if (!datas) datas = [];
  let start_date = dateRange[0];

  let start = moment(start_date).startOf("day");
  let end = moment(start_date).endOf("day");

  for (let m = start; m.isBefore(end); m.add(1, "hours")) {
    let _date = m.format("YYYY-MM-DD HH:00:00");
    let target = datas.find((item) => item.date == _date);
    if (target) {
      yAxis.push(target.value);
    } else {
      yAxis.push(0);
    }
    xAxis.push(m.format("H点"));
  }

  return getEchartConfig(xAxis, yAxis);
}

function getWeekEchartData(datas = [], dateRange) {
  let [start_date, end_date] = dateRange;
  let startDateMoment = moment(start_date);
  let endDateMoment = moment(end_date);

  let start = startDateMoment.startOf("isoWeek").format("YYYY-MM-DD");
  let end = endDateMoment.endOf("isoWeek").format("YYYY-MM-DD");

  let current = start;
  const days = [];
  while (current <= end) {
    days.push(current);
    current = moment(current).add(1, "days").format("YYYY-MM-DD");
  }

  if (!datas) datas = [];
  let xAxis = [];
  let yAxis = [];
  for (let i = 0; i < days.length; i++) {
    let _date = days[i];
    let target = datas.find((item) => item.date == _date);
    if (target) {
      yAxis.push(target.value);
    } else {
      yAxis.push(0);
    }
    let week = weeks[i];
    _date = moment(_date).format("MM-DD");
    xAxis.push(week + "\n(" + _date + ")");
  }
  return getEchartConfig(xAxis, yAxis);
}

export function getMonthEchartData(datas = [], dateRange, isYear = false) {
  let [start_date, end_date] = dateRange;
  let startDateMoment = moment(start_date);
  let endDateMoment = moment(end_date);
  const days = endDateMoment.diff(startDateMoment, "days") + 1;
  if (!datas) datas = [];
  let xAxis = [];
  let yAxis = [];
  for (let i = 0; i < days; i++) {
    let _date = startDateMoment.clone().add(i, "days").format("YYYY-MM-DD");
    let target = datas.find((item) => item.date == _date);
    if (target) {
      yAxis.push(target.value);
    } else {
      yAxis.push(0);
    }
    if (isYear) {
      _date = moment(_date).format("YYYY-MM-DD");
    } else {
      _date = moment(_date).format("MM-DD");
    }

    xAxis.push(_date);
  }
  return getEchartConfig(xAxis, yAxis);
}

export function getEchartConfig(xAxis = [], yAxis = []) {
  return {
    grid: {
      left: 20,
      right: 20,
      bottom: 15,
      top: 20,
      containLabel: true,
    },
    xAxis: [
      {
        type: "category",
        axisLine: {
          lineStyle: {
            color: "#999999",
          },
        },
        axisLabel: {
          color: "#666666",
        },
        data: xAxis,
      },
    ],
    yAxis: {
      type: "value",
      axisLabel: {
        formatter: "{value}",
      },
    },
    series: [
      {
        name: "分值",
        type: "line",
        data: yAxis,
        smooth: true,
        label: {
          show: true,
          position: "top",
        },
      },
    ],
    dataZoom: [
      {
        type: "inside",
        start: 0,
        end: 100,
        minSpan: 8,
      },
    ],
  };
}

function getYearEchartData(datas = [], dateRange) {
  let date = moment(dateRange[0]);
  if (!datas) datas = [];
  const dates = [];
  for (let i = 0; i < 12; i++) {
    dates.push(date.month(i).format("YYYY-MM-DD"));
  }
  console.log("dates", dates);
  let xAxis = [];
  let yAxis = [];
  for (let i = 0, len = dates.length; i < len; i++) {
    let _date = dates[i];
    let target = datas.find((item) => _date.startsWith(item.date));
    if (target) {
      yAxis.push(target.value);
    } else {
      yAxis.push(0);
    }
    _date = moment(_date).format("MM月");
    xAxis.push(_date);
  }
  return getEchartConfig(xAxis, yAxis);
}

export function getEchartsData(data = [], dateRange, type) {
  console.log("data, dateRange, type", data, dateRange, type);

  switch (type) {
    case "day": {
      return getDayEchartData(data, dateRange, type);
    }
    case "week": {
      return getWeekEchartData(data, dateRange, type);
    }
    case "month": {
      return getMonthEchartData(data, dateRange, type);
    }
    case "year": {
      return getYearEchartData(data, dateRange, type);
    }
  }
}

export function getParams(
  target = {},
  keys = [],
  defaultKey,
  excludeKeys = []
) {
  let param = {};
  let otherParam = {};
  for (let key in target) {
    if (excludeKeys.includes(key)) continue;
    if (!keys.includes(key)) {
      otherParam[key] = target[key];
      continue;
    }
    if (target[key]) {
      param[key] = target[key];
    }
  }

  if (Object.keys(param).length <= 0) {
    param[defaultKey] = "--all--";
  }

  return {
    ...otherParam,
    ...param,
  };
}

export function getMonthRange(date) {
  const startOfMonth = moment(date).startOf("month").format("YYYY-MM-DD");
  const endOfMonth = moment(date).endOf("month").format("YYYY-MM-DD");
  return [startOfMonth, endOfMonth];
}

export function getCurRoutePath(pages) {
  const currentPage = pages[pages.length - 1]; // 获取当前页面的对象
  const route = currentPage.route; // 当前页面的路由
  return route;
}

function getPreMonth(date, appointDay = 1) {
  let { year, month } = date;
  if (month === 1) {
    year -= 1;
    month = 12;
  } else {
    month -= 1;
  }

  return { year, month, day: appointDay };
}
function getNextMonth(appointDay = 1, dateInfo = {}) {
  let { year, month } = dateInfo;
  if (month === 12) {
    year += 1;
    month = 1;
  } else {
    month += 1;
  }

  return { year, month, day: appointDay };
}

export function getMonthData(date) {
  const { year, month } = date;
  let dataArr = [];
  let daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

  if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
    daysInMonth[1] = 29;
  }

  const monthStartWeekDay = new Date(year, month - 1, 1).getDay();
  const monthEndWeekDay = new Date(year, month, 1).getDay() || 7;

  const preInfo = getPreMonth(date);
  const nextInfo = getNextMonth(1, date);

  for (let i = 1; i < monthStartWeekDay; i++) {
    let day = daysInMonth[preInfo.month - 1] - (monthStartWeekDay - i - 1);
    dataArr.push(
      moment(preInfo.year + "/" + preInfo.month + "/" + day).format(
        "YYYY-MM-DD"
      )
    );
  }

  for (let i = 0; i < daysInMonth[month - 1]; i++) {
    dataArr.push(
      moment(year + "/" + month + "/" + (i + 1)).format("YYYY-MM-DD")
    );
  }

  let len = 7 - monthEndWeekDay;

  if (dataArr.length + 7 < 42) {
    //需要补全一个周
    len += 7;
  }

  for (let i = 0; i <= len; i++) {
    dataArr.push(
      moment(nextInfo.year + "/" + nextInfo.month + "/" + (i + 1)).format(
        "YYYY-MM-DD"
      )
    );
  }
  return dataArr;
}


export function strip(num, precision) {
  return toFixed(num, precision);
}


export function pageRouter(path) {
  let pages = getCurrentPages();
  console.log("pages", pages)
  let index = pages.findIndex((item) => path == ("/" + item.route));
  if (index == pages.length - 1) return;
  if (index > 0) {
    uni.navigateBack({
      delta: index,
    });
  } else {
    uni.navigateTo({
      url: path,
    });
  }
}

export function generateStr(len = 26) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  const charactersLength = characters.length;

  for (let i = 0; i < len; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

export function getRouteParams() {
  const pages = getCurrentPages();
  let curPage = pages[pages.length - 1];
  if (!curPage) return;
  let path = curPage.$page.fullPath;
  const urlParsed = qs.parse(path.split("?")[1]);
  return urlParsed;
}